// pages/user/settings/settings.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  submitHead(options) {
    let that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        let path = res.tempFiles[0].tempFilePath;
        that.setData({
          headurl: path,
        });
        wx.showLoading();
        wx.uploadFile({
          url: 'https://api.fracher21.top/spotit-static/upload',
          filePath: path,
          name: 'image',
          formData: {
            'category': 'head',
          },
          success: (res) => {
            wx.hideLoading();
            let url = JSON.parse(res.data).url;
            that.updateUserInfo("head", url, () => {
              that.updateData();
            })
          },
          fail: (res) => {
            console.log("fail: ", res);
          }
        })
      }
    });
  },

  submitName(options) {
    let value = options.detail.value;
    let that = this;
    this.updateUserInfo("name", value, () => {
      that.updateData();
    })
  },

  submitMotto(options) {
    let value = options.detail.value;
    let that = this;
    this.updateUserInfo("motto", value, () => {
      that.updateData();
    })
  },

  updateUserInfo(field, value, update) {
    let app = getApp();
    wx.request({
      url: 'https://api.fracher21.top/spotit/setuserinfo',
      method: 'POST',
      data: {
        token: app.globalData.token,
        field: field,
        value: value
      },
      success: (res) => {
        // console.log(res.data);
        update();
      }
    })
  },

  updateData() {
    let that = this;
    let app = getApp();
    wx.request({
      url: 'https://api.fracher21.top/spotit/getuserinfo',
      method: 'GET',
      data: {
        token: app.globalData.token,
      },
      success: (res) => {
        let data = res.data;
        that.setData({
          username: data.name,
          headurl: data.head,
          motto: data.motto,
          id: data.id,
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.updateData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})